/**
 * Created by kahn on 2020/02/26.
 */
import Axios from 'axios';

/**
 * 各类校验集合fn
 * @param   [{string/number}]   p    [校验内容，必填]
 * @param   [{string}]    t    [校验类型，非必填]
 */
const regExp = (p, t = 'mp') => {        // 正則判断
    switch(t){
        case 'mp':                      // 驗證手機號
            return /^1[3,4,5,7,8]{1}[0-9]{9}$/.test(p);
        case 'tel':                     // 座机号
            return /^0[\d]{2,3}-[\d]{7,8}$/.test(p);
        case 'id':
            return /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(p);
        default:
            return;
    }
};

/**
 * 函数节流 防止连续重复调用
 * @param   [{function}]   fn    [要执行函数]
 * @param   [{number}]   t    [控制节流的周期]
 */
const throttle = (fn, t = 500) => {
    let last, timer, interval = t;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
}

/**
 * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 * 
 * @param num1加数1 | num2加数2
 */
const numAdd = (num1, num2) => {
    let baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
};

/**
 * 减法运算，避免数据相减小数点后产生多位数和计算精度损失。
 * 
 * @param num1被减数  |  num2减数
 */
const numSub = (num1, num2) => {
    let baseNum, baseNum1, baseNum2;
    let precision;// 精度
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};

/**
 * 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
 * 
 * @param num1被乘数 | num2乘数
 */
const numMulti = (num1, num2) => {
    let baseNum = 0;
    try {
        baseNum += num1.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        baseNum += num2.toString().split(".")[1].length;
    } catch (e) {
    }
    return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
};

/**
 * 除法运算，避免数据相除小数点后产生多位数和计算精度损失。
 * 
 * @param num1被除数 | num2除数
 */
const numDiv = (num1, num2) => {
    let baseNum1 = 0, baseNum2 = 0;
    let baseNum3, baseNum4;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum3 = Number(num1.toString().replace(".", ""));
    baseNum4 = Number(num2.toString().replace(".", ""));
    return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1);
};

// 该样式文件位于@/assets/css/components/_load.scss
const loadIn = (t = '正在加载...') => {
    if (window.load){
        return;
    }
    window.load = document.createElement('div');
    window.load.className = 'load-block';
    window.load.innerHTML = `<div class="load"><i></i><span>${t}</span></div>`;
    document.body.appendChild(window.load);
};

// 该样式文件位于@/assets/css/components/_load.scss
const loadOut = () => {
    "use strict";
    if (!window.load){
        return;
    }
    window.load.classList.add('fade-out');
    let _t = setTimeout(() => {
        try {
            document.body.removeChild(window.load);
            clearTimeout(_t);
        }
        catch(e){}
        finally {
            window.load = void 0;
        }
    }, 250);
};

// 该样式文件位于@/assets/css/components/_toast.scss
const toast = (t, fn) => {
    "use strict";
    if (window.tip){
        return;
    }
    window.tip = document.createElement('div');
    window.tip.className = 'toast-block';
    window.tip.innerHTML = `<div class="toast"><p>${t}</p></div>`;
    document.body.appendChild(window.tip);
    setTimeout(() => {
        if (!window.tip){
            return;
        }
        window.tip.classList.add('fade-out');
        setTimeout(() => {
            try {
                document.body.removeChild(window.tip);
            }catch(e){}
            finally {
                window.tip = void 0;
            }
            fn && fn();
        }, 350);
    }, 1000);
};

/**
 * 通过微信code获取用户信息并登陆
 * 
 * @param code
 */
const getLogin = (code) => {
    return new Promise((resolve, reject) => {
        let config = {
            headers:{'Content-Type': 'multipart/form-data'}
        };  //添加请求头
        Axios.get(`${window.config['WxGetOpenId']}`, {
            params: {
                code: code
            }
        }, config)
        .then(response => {
            resolve(response.data);
        })
        .catch(e => {
            reject(e);
        });
    })      
}


export { regExp, throttle, numAdd, numSub, numMulti, numDiv, loadIn, loadOut, toast, getLogin }